# -*- coding:utf-8 -*-
'''
@Author: lindes
'''
import re
import uuid
from django.http import JsonResponse
from BasketballCommunity.settings import TOKEN_EXPIRE
from users.models import UserToken
from datetime import timedelta, datetime


def create_token(user_obj):
    """
    生成token
    :param user_obj: user对象
    :return: token
    """
    u = uuid.uuid4()
    token = str(u).replace('-', '')
    user_token = UserToken(user=user_obj, token=token)
    try:
        user_token.save()
        return token
    except:
        return None


def check_token(token):
    """
    检查token有效性
    :param token: token
    :return: user_id
    """
    token = UserToken.objects.filter(token=token).last()
    if token:
        if token.add_time > datetime.now() - TOKEN_EXPIRE:
            return token.user
        else:
            return False
    else:
        return False


# 装饰器:判断提交的method
def check_method(method: str):
    def inner(func):
        def warpper(*args, **kwargs):
            method.upper()
            if args[0].method == method:
                result = func(*args, **kwargs)
                return result
            return JsonResponse({'code': 1000, 'msg': '请求方法错误', 'data': 0})
        return warpper
    return inner


# 装饰器:检查POST方法中是否有token
def has_token(func):
    def warpper(*args, **kwargs):
        if args[0].POST.get('token', None):
            return func(*args, **kwargs)
        return JsonResponse({'code': 1000, 'msg': '无效的令牌', 'data': 0})
    return warpper


# # 装饰器:检查token是否过期
# def token_alive(func):
#     def warpper(*args, **kwargs):
#         token = args[0].POST.get('token', None)
#         usr_token = UserToken.objects.filter(token=token).last()
#         if usr_token:
#             if token.add_time > datetime.now() - TOKEN_EXPIRE:
#                 token.user.id
#                 return func(*args, **kwargs)
#             else:
#                 return False
#         return JsonResponse({'code': 1000, 'msg': '无效的令牌', 'data': 0})
#     return warpper


# 检查密码格式是否合法
def pwd_isvalid(pwd):
    match = 0
    patterns = ['[a-z]', '[A-Z]', '[0-9]', '[\(\)\~\!\@\#\$\%\^\&\*\-\+\=\_\|\{\}\[\]\:\;\,\.\?\/]']
    for pattern in patterns:
        if re.search(pattern, pwd):
            match += 1
    if match >= 3:
        return True
    else:
        return False
